﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;

namespace RedRiver.Framework.XtraCommon.FastReflection{
    public interface IConstructorInvoker{
        object Invoke(params object[] parameters);
    }

    public class ConstructorInvoker : IConstructorInvoker{
        private readonly Func<object[], object> _invoker;

        public ConstructorInvoker(ConstructorInfo constructorInfo){
            ConstructorInfo = constructorInfo;
            _invoker = InitializeInvoker(constructorInfo);
        }

        public ConstructorInfo ConstructorInfo{
            get;
            private set;
        }

        #region IConstructorInvoker Members

        object IConstructorInvoker.Invoke(params object[] parameters){
            return Invoke(parameters);
        }

        #endregion

        private Func<object[], object> InitializeInvoker(ConstructorInfo constructorInfo){
            // Target: (object)new T((T0)parameters[0], (T1)parameters[1], ...)

            // parameters to execute
            ParameterExpression parametersParameter = Expression.Parameter(typeof (object[]), "parameters");

            // build parameter list
            var parameterExpressions = new List<Expression>();
            ParameterInfo[] paramInfos = constructorInfo.GetParameters();
            for (int i = 0; i < paramInfos.Length; i++){
                // (Ti)parameters[i]
                BinaryExpression valueObj = Expression.ArrayIndex(parametersParameter, Expression.Constant(i));
                UnaryExpression valueCast = Expression.Convert(valueObj, paramInfos[i].ParameterType);

                parameterExpressions.Add(valueCast);
            }

            // new T((T0)parameters[0], (T1)parameters[1], ...)
            NewExpression instanceCreate = Expression.New(constructorInfo, parameterExpressions);

            // (object)new T((T0)parameters[0], (T1)parameters[1], ...)
            UnaryExpression instanceCreateCast = Expression.Convert(instanceCreate, typeof (object));

            Expression<Func<object[], object>> lambda = Expression.Lambda<Func<object[], object>>(instanceCreateCast,
                                                                                                  parametersParameter);

            return lambda.Compile();
        }

        public object Invoke(params object[] parameters){
            return _invoker(parameters);
        }
    }
}